'use strict';

import React from 'react';
import {
  View,
  ImageBackground,
  Platform,
  StyleSheet,
  Dimensions,
  Text,
} from 'react-native';

import MoreDialog from './MoreDialog';
import { Package, Device, DeviceEvent, Host, Service, SceneType } from "miot";
import CommonSelectButton from './CommonSelectButton'
import TitleBarWhite from 'miot/ui/TitleBarWhite';
import CustomImageButton from './CustomImageButton';

export default class MainPage extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      relayTimerName: "",
      relayTimerMsg: "",
      mrTimerName: "",
      mrTimerMsg: "",
      lightTimerName: "",
      lightTimerMsg: "",
      relayPwrButtonSelected: false,
      mosquitoRepellentPwrButtonSelected: false,
      lightPwrButtonSelected: false,
    }
  }

  static navigationOptions = ({ navigation }) => {
    return {
      header:
        <View>
          <TitleBarWhite
            title={navigation.state["params"] ? navigation.state.params.name : Device.name}
            style={{ backgroundColor: '#0F084D' }}
            onPressLeft={() => { Package.exit() }}
            onPressRight={() => {
              if (Platform.OS == 'android') {
                navigation.setParams({ showDialog: true });
              } else {
                navigation.navigate('moreMenu', { 'title': '设置' });
              }
            }} />
          <MoreDialog
            visible={typeof navigation.state.params === 'undefined' ? false : navigation.state.params.showDialog}
            navigation={navigation} />
        </View>
    };
  };

  // 获取某个元素下标
  contains(arrays, obj) {
    var i = arrays.length;
    while (i--) {
      if (arrays[i] === obj) {
        return i;
      }
    }
    return false;
  }

  // 获取定时设置信息
  getTimerList() {
    Service.scene.loadScenes(Device.deviceID, SceneType.Timer)
      .then((sceneArr) => {
        console.log(sceneArr);
        // 获取系统时间及相应的时间戳信息。
        var ostime = new Date();
        var osyear = ostime.getFullYear();
        var osmonth = ostime.getMonth() + 1;
        var osdate = ostime.getDate();
        var osTimestamp = Date.parse(ostime) / 1000;
        var minOffTimer = osTimestamp;
        var minOnTimer = osTimestamp;
        var minTimer;

        // 定义周期定时中时，分变量
        var onmonth;
        var ondate;
        var onhours;
        var onminutes;
        var offmonth;
        var offdate;
        var offhours;
        var offminutes;

        var ontimerTime;
        var ontimerTimestamp;
        var offtimerTime;
        var offtimerTimestamp;

        var timerDic00 = new Array();
        var timerDic01 = new Array();
        var timerDic02 = new Array();
        var groupTimerDic = new Array();

        if (sceneArr.length > 0) {
          for (var i = 0; i < sceneArr.length; i++) {
            var timerItem = sceneArr[i];
            var timerSetting = timerItem["setting"];
            // 如果定时标识位为0，则跳过
            if (timerSetting["enable_timer"] == 0) {
              this.setState({
              relayTimerMsg: "",
              mrTimerMsg: "",
              lightTimerMsg: ""
            })
              continue;
            }
            // 清空定时展示信息。
            this.setState({
              relayTimerMsg: "",
              mrTimerMsg: "",
              lightTimerMsg: ""
            })
            // 获取定时执行参数
            var params = timerSetting["off_param"];
            // 获取定时时间
            var ontime = timerSetting["on_time"];
            var offtime = timerSetting["off_time"];
            onhours = ontime.split(" ")[1];
            onminutes = ontime.split(" ")[0]
            offhours = offtime.split(" ")[1]
            offminutes = offtime.split(" ")[0]
            if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") {
              onmonth = osmonth
              ondate = osdate
              offmonth = osmonth
              offdate = osdate
            } else {
              onmonth = ontime.split(" ")[3]
              ondate = ontime.split(" ")[2]
              offmonth = offtime.split(" ")[3]
              offdate = offtime.split(" ")[2]
            }
            // 获取参数数组中参数的下标位置
            var index;
            if (typeof(params) === typeof("abc")) { //说明是通过iOS设置的参数需要JSON序列化
              var tempObj = JSON.parse(params)
              index = this.contains(tempObj, "0");
            }else { //说明是通过android设置的参数，可以直接使用
              index = this.contains(params, "0");
            }
            console.log(index, params);
            // 根据下标位置对定时数据进行分组
            if (index === 0) { //插座定时
              onhours = ontime.split(" ")[1]
              offhours = offtime.split(" ")[1]
              if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 1) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  ontimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onminutes + ":00"
                } else { // 单次执行定时
                  ontimerTime = osyear + "/" + onmonth + "/" + ondate + " " + onhours + ":" + onminutes + ":00"
                }
                ontimerTimestamp = Date.parse(ontimerTime) / 1000;
                minOnTimer = ontimerTimestamp - osTimestamp
                minTimer = minOnTimer
                // 将信息保存到dic中
                timerDic00[minTimer.toString()] = timerItem;
              } else if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 0) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  offtimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onhours + ":00"
                } else { // 单次执行定时
                  offtimerTime = osyear + "/" + offmonth + "/" + offdate + " " + offhours + ":" + offminutes + ":00"
                }
                offtimerTimestamp = Date.parse(offtimerTime) / 1000;
                minOffTimer = offtimerTimestamp - osTimestamp;
                minTimer = minOffTimer;
                // 将信息保存到dic中
                timerDic00[minTimer.toString()] = timerItem;
              } else if (timerSetting["enable_timer_off"] == 0 && timerSetting["enable_timer_on"] == 1) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  ontimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onminutes + ":00"
                } else { // 单次执行定时
                  ontimerTime = osyear + "/" + onmonth + "/" + ondate + " " + onhours + ":" + onminutes + ":00"
                }
                ontimerTimestamp = Date.parse(ontimerTime) / 1000;
                minOnTimer = ontimerTimestamp - osTimestamp;
                minTimer = minOnTimer;
                // 将信息保存到dic中
                timerDic00[minTimer.toString()] = timerItem;
              }
              groupTimerDic["0"] = timerDic00;
            } else if (index === 1) {//电蚊香定时
              onhours = ontime.split(" ")[1]
              offhours = offtime.split(" ")[1]
              if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 1) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  ontimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onminutes + ":00"
                } else { // 单次执行定时
                  ontimerTime = osyear + "/" + onmonth + "/" + ondate + " " + onhours + ":" + onminutes + ":00"
                }
                ontimerTimestamp = Date.parse(ontimerTime) / 1000;
                minOnTimer = ontimerTimestamp - osTimestamp
                minTimer = minOnTimer
                // 将信息保存到dic中
                timerDic01[minTimer.toString()] = timerItem;
              } else if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 0) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  offtimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onhours + ":00"
                } else { // 单次执行定时
                  offtimerTime = osyear + "/" + offmonth + "/" + offdate + " " + offhours + ":" + offminutes + ":00"
                }
                offtimerTimestamp = Date.parse(offtimerTime) / 1000;
                minOffTimer = offtimerTimestamp - osTimestamp;
                minTimer = minOffTimer;
                // 将信息保存到dic中
                timerDic01[minTimer.toString()] = timerItem;
              } else if (timerSetting["enable_timer_off"] == 0 && timerSetting["enable_timer_on"] == 1) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  ontimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onminutes + ":00"
                } else { // 单次执行定时
                  ontimerTime = osyear + "/" + onmonth + "/" + ondate + " " + onhours + ":" + onminutes + ":00"
                }
                ontimerTimestamp = Date.parse(ontimerTime) / 1000;
                minOnTimer = ontimerTimestamp - osTimestamp;
                minTimer = minOnTimer;
                // 将信息保存到dic中
                timerDic01[minTimer.toString()] = timerItem;
              }
              groupTimerDic["1"] = timerDic01;
            } else if (index === 2) {//夜灯定时
              onhours = ontime.split(" ")[1]
              offhours = offtime.split(" ")[1]
              if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 1) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  ontimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onminutes + ":00"
                } else { // 单次执行定时
                  ontimerTime = osyear + "/" + onmonth + "/" + ondate + " " + onhours + ":" + onminutes + ":00"
                }
                ontimerTimestamp = Date.parse(ontimerTime) / 1000;
                minOnTimer = ontimerTimestamp - osTimestamp
                minTimer = minOnTimer
                // 将信息保存到dic中
                timerDic02[minTimer.toString()] = timerItem;
              } else if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 0) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  offtimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onhours + ":00"
                } else { // 单次执行定时
                  offtimerTime = osyear + "/" + offmonth + "/" + offdate + " " + offhours + ":" + offminutes + ":00"
                }
                offtimerTimestamp = Date.parse(offtimerTime) / 1000;
                minOffTimer = offtimerTimestamp - osTimestamp;
                minTimer = minOffTimer;
                // 将信息保存到dic中
                timerDic02[minTimer.toString()] = timerItem;
              } else if (timerSetting["enable_timer_off"] == 0 && timerSetting["enable_timer_on"] == 1) {
                if (ontime.split(" ").slice(-1) != "*" || offtime.split(" ").slice(-1) != "*") { // 如果不等于*号字符，则表示是重复执行逻辑。
                  // 接口中重复定时只有时，分信息，所以要自己拼时间成yyyy-MM-DD hh:mm:ss的形势
                  ontimerTime = osyear + "/" + osmonth + "/" + osdate + " " + onhours + ":" + onminutes + ":00"
                } else { // 单次执行定时
                  ontimerTime = osyear + "/" + onmonth + "/" + ondate + " " + onhours + ":" + onminutes + ":00"
                  // var offtimerTime = osyear + "/" + offmonth + "/" + offdate + " " + offhours + ":" + offminutes + ":00"
                }
                ontimerTimestamp = Date.parse(ontimerTime) / 1000;
                minOnTimer = ontimerTimestamp - osTimestamp;
                minTimer = minOnTimer;
                // 将信息保存到dic中
                timerDic02[minTimer.toString()] = timerItem;
              }
              groupTimerDic["2"] = timerDic02;
            }
          }

          // 整个for循环结构后，已将定时信息进行了分组
          for (var key in groupTimerDic) {
            if (key == "0") {
              var relaytimerInfo = groupTimerDic["0"];
              var relaytimerItem = this.getObjectValues(relaytimerInfo)[0];
              var relaytimerRes = this.getCurrentTimerInfo(relaytimerItem);
              this.setState({ relayTimerMsg: relaytimerRes });
            } else if (key == "1") {
              var mrtimerInfo = groupTimerDic["1"];
              var mrtimerItem = this.getObjectValues(mrtimerInfo)[0];
              var mrtimerRes = this.getCurrentTimerInfo(mrtimerItem);
              this.setState({ mrTimerMsg: mrtimerRes });
            } else if (key == "2") {
              var lighttimerInfo = groupTimerDic["2"];
              var lighttimerItem = this.getObjectValues(lighttimerInfo)[0];
              var lighttimerRes = this.getCurrentTimerInfo(lighttimerItem);
              this.setState({ lightTimerMsg: lighttimerRes });
            }
          }
        }else {
          this.setState({
            relayTimerMsg: "",
            mrTimerMsg: "",
            lightTimerMsg: ""
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      });
  }

  // 获取字典中的Values
  getObjectValues(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  }

  // 获取最近一次要执行的定时信息
  getCurrentTimerInfo(object) {
    var timerMsg;
    var onTimerInfo = "";
    var offTimerInfo = "";
    var timerSetting = object["setting"]

    var onTempStr;
    var offTempStr;
    if (timerSetting["on_time"].split(" ")[0].length === 1) {
      onTempStr = "0" +  timerSetting["on_time"].split(" ")[0];
    }else {
      onTempStr = timerSetting["on_time"].split(" ")[0];
    }

    if (timerSetting["off_time"].split(" ")[0].length === 1) {
      offTempStr = "0" + timerSetting["off_time"].split(" ")[0];
    }else {
      offTempStr = timerSetting["off_time"].split(" ")[0];
    }

    if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 1) { //该定时为时间段定时，并且开一定早于关
      
      onTimerInfo = timerSetting["on_time"].split(" ")[1] + ":" + onTempStr
      offTimerInfo = timerSetting["off_time"].split(" ")[1] + ":" + offTempStr
      timerMsg = "定时开" + "\n" + onTimerInfo + "\n" + "定时关" + "\n" + offTimerInfo
    } else if (timerSetting["enable_timer_off"] == 0 && timerSetting["enable_timer_on"] == 1) { //执行定时开操作

      onTimerInfo = timerSetting["on_time"].split(" ")[1] + ":" + onTempStr
      timerMsg = "定时开" + "\n" + onTimerInfo
    } else if (timerSetting["enable_timer_off"] == 1 && timerSetting["enable_timer_on"] == 0) { //执行定时关操作

      offTimerInfo = timerSetting["off_time"].split(" ")[1] + ":" + offTempStr
      timerMsg = "定时关" + "\n" + offTimerInfo
    }
    return timerMsg;
  }

  // 获取各电器的状态，设置对应的按钮状态
  getDeviceState() {
    Device.getDeviceWifi().callMethod("GetState", []).then(res => {
      // console.log(res.result)
      if (res.result[0] == "1") { //断电器开
        this.setState({
          relayPwrButtonSelected: true
        });
      } else { //断电器关
        this.setState({
          relayPwrButtonSelected: false
        });
      }
      if (res.result[1] == "1") { //蚊香开
        this.setState({
          mosquitoRepellentPwrButtonSelected: true
        });
      } else { //蚊香关
        this.setState({
          mosquitoRepellentPwrButtonSelected: false
        });
      }
      if (res.result[2] == "1") { //夜灯开
        this.setState({
          lightPwrButtonSelected: true
        });
      } else { //夜灯关
        this.setState({
          lightPwrButtonSelected: false
        });
      }
    }).catch(err => {
      console.log(err.error, err.message);
    });
  }

  // 获取用户操作历史记录(没有实现)
  getHistory() {
    Device.getDeviceWifi().callMethod("GetHistory", []).then(res => {
      console.log(res.result);
    }).catch(err => {
      console.log(err.error, err.message);
    })
  }

  // 组件将被加载时调用
  componentWillMount() {
    this.getTimerList();
    this.getDeviceState();
    // 开启定时任务
    this.timer = setInterval(() => {
      this.getTimerList();
      this.getDeviceState();
    }, 10000);

    // 监控设备名称是否被修改
    this._deviceNameChangedListener = DeviceEvent.deviceNameChanged.addListener((device) => {
      this.props.navigation.setParams({
        name: device.name
      });
      this.forceUpdate();
    });

    this._deviceStatusChangedListener = DeviceEvent.deviceStatusChanged.addListener((device) => {
      console.log('_deviceStatusChangedListener', device);
      this.forceUpdate();
    });

  }

  // 组件被卸载时调用此方法
  componentWillUnmount() {
    // 当组件被卸载时，清除监听器和定时器
    this._deviceNameChangedListener.remove();
    this.timer && clearInterval(this.timer);
    this.delay && clearInterval(this.delay);
  }

  // 组件加载完成时调用此方法
  componentDidMount() {

  }

  // 渲染组件
  render() {
    return (
      <ImageBackground style={styles.bgimageStyle} source={require("../Resources/title/bg.png")} >
        <Text style={styles.textStyleTop}>插座控制</Text>
        <ImageBackground style={styles.switchimageStyle} resizeMode='stretch' source={require("../Resources/title/switch.png")} >
          <CommonSelectButton imageUri={require('../Resources/title/close.png')}
            selectedImageUri={require('../Resources/title/open.png')}
            selected={this.state.relayPwrButtonSelected}
            imageStyle={styles.pwrOnButtonStyle}
            onPressIn={this.pwrButtonPressForRelay.bind(this)}
          />
          <CustomImageButton
            style={styles.timerButtonStyle}
            source={require('../Resources/title/tclose.png')}
            highlightedSource={require('../Resources/title/topen.png')}
            onPress={() => this.timerButtonPressForRelay()}
          />
          <View style={styles.timerViewStyle}>
            <Text style={styles.timerTitleTextStyle}>定时信息</Text>
            <Text style={styles.timerInfoTextStyle}>{this.state.relayTimerMsg}</Text>
          </View>
        </ImageBackground>

        <Text style={styles.textStyle}>电蚊香液加热器</Text>
        <ImageBackground style={styles.switchimageStyle} resizeMode='stretch' source={require("../Resources/title/switch.png")} >
          <CommonSelectButton imageUri={require('../Resources/title/close.png')}
            selectedImageUri={require('../Resources/title/open.png')}
            selected={this.state.mosquitoRepellentPwrButtonSelected}
            imageStyle={styles.pwrOnButtonStyle}
            onPressIn={this.pwrButtonPressFroMosquitoRepellent.bind(this)}
          />
          <CustomImageButton
            style={styles.timerButtonStyle}
            source={require('../Resources/title/tclose.png')}
            highlightedSource={require('../Resources/title/topen.png')}
            onPress={() => this.timerButtonPressForMosquitoRepellent()}
          />
          <View style={styles.timerViewStyle}>
            <Text style={styles.timerTitleTextStyle}>定时信息</Text>
            <Text style={styles.timerInfoTextStyle}>{this.state.mrTimerMsg}</Text>
          </View>
        </ImageBackground>

        <Text style={styles.textStyle}>LED灯控制</Text>
        <ImageBackground style={styles.switchimageStyle} resizeMode='stretch' source={require("../Resources/title/switch.png")} >
          <CommonSelectButton imageUri={require('../Resources/title/close.png')}
            selectedImageUri={require('../Resources/title/open.png')}
            selected={this.state.lightPwrButtonSelected}
            imageStyle={styles.pwrOnButtonStyle}
            onPressIn={this.pwrButtonPressForLight.bind(this)}
          />
          <CustomImageButton
            style={styles.timerButtonStyle}
            source={require('../Resources/title/tclose.png')}
            highlightedSource={require('../Resources/title/topen.png')}
            onPress={() => this.timerButtonPressForLight()}
          />
          <View style={styles.timerViewStyle}>
            <Text style={styles.timerTitleTextStyle}>定时信息</Text>
            <Text style={styles.timerInfoTextStyle}>{this.state.lightTimerMsg}</Text>
          </View>
        </ImageBackground>
      </ImageBackground>
    )
  }

  // 断电器按钮点击事件
  pwrButtonPressForRelay(button) {
    var selectedStatus = this.state.relayPwrButtonSelected;
    if (selectedStatus) {
      Device.getDeviceWifi().callMethod("SetStateNew", ["0", " ", " "]).then(res => {
        console.log(res.result[0]);
        if (res.result[0] == "ok") {
          button.setState({
            selected: !selectedStatus
          })
          this.setState({
            relayPwrButtonSelected: !selectedStatus
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      })
    } else {
      Device.getDeviceWifi().callMethod("SetStateNew", ["1", " ", " "]).then(res => {
        console.log(res.result[0]);
        if (res.result[0] == "ok") {
          button.setState({
            selected: !selectedStatus
          })
          this.setState({
            relayPwrButtonSelected: !selectedStatus
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      })
    }
  }

  // 蚊香按钮点击事件
  pwrButtonPressFroMosquitoRepellent(button) {
    var selectedStatus = this.state.mosquitoRepellentPwrButtonSelected;
    if (selectedStatus) {
      Device.getDeviceWifi().callMethod("SetStateNew", [" ", "0", " "]).then(res => {
        console.log(res.result[0]);
        if (res.result[0] == "ok") {
          button.setState({
            selected: !selectedStatus
          })
          this.setState({
            mosquitoRepellentPwrButtonSelected: !selectedStatus
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      })
    } else {
      Device.getDeviceWifi().callMethod("SetStateNew", [" ", "1", " "]).then(res => {
        console.log(res.result[0]);
        if (res.result[0] == "ok") {
          button.setState({
            selected: !selectedStatus
          })
          this.setState({
            mosquitoRepellentPwrButtonSelected: !selectedStatus
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      })
    }
  }

  // 夜灯按钮点击事件
  pwrButtonPressForLight(button) {
    var selectedStatus = this.state.lightPwrButtonSelected;
    if (selectedStatus) {
      Device.getDeviceWifi().callMethod("SetStateNew", [" ", " ", "0"]).then(res => {
        console.log(res.result[0]);
        if (res.result[0] == "ok") {
          button.setState({
            selected: !selectedStatus
          })
          this.setState({
            lightPwrButtonSelected: !selectedStatus
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      })
    } else {
      Device.getDeviceWifi().callMethod("SetStateNew", [" ", " ", "1"]).then(res => {
        console.log(res.result[0]);
        if (res.result[0] == "ok") {
          button.setState({
            selected: !selectedStatus
          })
          this.setState({
            lightPwrButtonSelected: !selectedStatus
          })
        }
      }).catch(err => {
        console.log(err.error, err.message);
      })
    }
  }

  // 设置断电器定时
  timerButtonPressForRelay = () => {
    // Host.ui.openTimerSettingPageWithVariousTypeParams("SetStateNew ", ["1", " ", " "], "SetStateNew", ["0", " ", " "]);
    Host.ui.openTimerSettingPageWithCustomIdentifier("Relay", "SetStateNew ", '["1", " ", " "]', "SetStateNew", '["0", " ", " "]');
  };

  // 设置蚊香定时
  timerButtonPressForMosquitoRepellent = () => {
    // Host.ui.openTimerSettingPageWithVariousTypeParams("SetStateNew", [" ", "1", " "], "SetStateNew", [" ", "0", " "]);
    Host.ui.openTimerSettingPageWithCustomIdentifier("Repellent", "SetStateNew ", '[" ", "1", " "]', "SetStateNew", '[" ", "0", " "]');
  };

  // 设置夜灯定时
  timerButtonPressForLight = () => {
    // Host.ui.openTimerSettingPageWithVariousTypeParams("SetStateNew", [" ", " ", "1"], "SetStateNew", [" ", " ", "0"]);
    Host.ui.openTimerSettingPageWithCustomIdentifier("Light", "SetStateNew ", '[" ", " ", "1"]', "SetStateNew", '[" ", " ", "0"]');
  };
}

// 设置样式
var styles = StyleSheet.create({
  bgimageStyle: {
    flex: 1,
    flexDirection: 'column',
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
  textStyleTop: {
    marginTop: 60,
    color: 'white',
    fontSize: 20,
    textAlign: 'left',
    marginLeft: 3,
  },
  textStyle: {
    marginTop: 20,
    color: 'white',
    fontSize: 20,
    textAlign: 'left',
    marginLeft: 3,
  },
  switchimageStyle: {
    flexDirection: 'row',
    alignItems: "center",
    width: '100%',
    height: 100,
  },
  timerTitleTextStyle: {
    marginLeft: 50,
    color: 'white',
    fontSize: 14,
    textAlign: 'left',
    fontWeight: "bold",
  },
  timerInfoTextStyle: {
    marginTop: 5,
    marginLeft: 50,
    color: 'white',
    fontSize: 12,
    textAlign: 'left',
  },
  timerTextStyle: {
    marginTop: 5,
    textAlign: "center",
    fontSize: 16,
  },
  timerButtonStyle: {
    width: 59,
    height: 59,
    marginLeft: 50,
  },
  pwrOnButtonStyle: {
    width: 59,
    height: 59,
    marginLeft: 30,
  },
});
